package com.eportal.filter;


import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;

import com.eportal.domain.Sysopt;
import com.eportal.util.WebUtil;

public class LoggerFilter implements Filter {

    private Logger log = Logger.getLogger(this.getClass().getName());


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    	
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    	try {
			HttpServletRequest req = (HttpServletRequest)request;
			if(!isExclude(req.getRequestURI())){
				Sysopt user = (Sysopt)req.getSession().getAttribute("user");
				String username = null;
				Long userid = null;
				if(user!=null){
					username = user.getUserName();
					userid = user.getSid();
				}
				String ua = req.getHeader("User-Agent");
				String logstr = "url="+WebUtil.getReqUrl(req)+",username="+username+",userid="+userid+",ip="+WebUtil.getIpAddr(req)+",ua="+ua;
				log.info(logstr);
				Map  params = req.getParameterMap();
				Iterator i = params.keySet().iterator();
				while (i.hasNext()) {
					String key = (String) i.next();
					String value = ((String[]) params.get(key))[0];
					log.info("paras:" + key + "=" + value);
				}
			}
		} catch (Exception e) {
			log.error(this, e);
		}
    	try{
    		chain.doFilter(request, response);	
    	}catch(Exception e){
    		log.error(this, e);
    	}
		
    }
    
    /**
     * 是不是要记录该请求，对于静态资源的请求暂时不记录
     * 
     * @param url
     * @return true 排除该请求，不记录
     */
    public boolean isExclude(String url){
    	String exclude = "js,css,png,jpg,jpeg,bmp,ico,gif";
    	if(url!=null){
    		String[] arr = exclude.split(",");
    		if(url.lastIndexOf(".")>-1&&url.lastIndexOf(".")<url.length()-1){
    			String ext = url.substring(url.lastIndexOf(".")+1);
    			for(String s:arr){
    				if(s.equals(ext)){
    					return true;
    				}
    			}
    		}
    	}
    	return false;
    }

    @Override
    public void destroy() {

    }
}
